﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace LightCAD.Core
{

    public static class Shape2dManager
    {
        public static Dictionary<Assembly, List<Type>> Providers;
        public static Shape2dProvider LoadProvider(string category)
        {
            if (Providers == null) InitProviders();

            var provider = new Shape2dProvider();
            foreach(var item in Providers)
            {
                foreach(var type in item.Value)
                {
                    try
                    {
                        var spObj = (IShape2dProvider)Activator.CreateInstance(type);
                        if(spObj!=null )
                        {
                            if(spObj.IsSupportCategory(category))
                                provider.AddShapes(spObj.GetShapes(category));
                        }
                        else
                        {
                            LcLog.Write(LogType.Warn, $"{type.FullName} can not be instanced.");
                        }

                    }catch(Exception ex)
                    {
                        LcLog.Write( LogType.Error, ex );
                    }
                }
            }
            return provider;
        }

        public static void InitProviders() {
            if (Providers == null)
            {
                Providers = new Dictionary<Assembly, List<Type>>(); 
            }
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();
            foreach (Assembly asm in assemblies)
            {
                var asmName = asm.GetName().Name;
                Debug.Assert(asmName != null, nameof(asmName) + " != null");

                if (!LcRuntime.RegistAssemblies.Contains(asmName)) continue;

                var types = asm.GetTypes();
                foreach (Type type in types)
                {
                    var shape2dProvider = type.GetInterface("IShape2dProvider");
                    if (shape2dProvider == null) continue;

                    if (Providers.ContainsKey(asm))
                    {
                        Providers[asm].Add(type);
                    }
                    else
                    {
                        var list = new List<Type>
                        {
                            type
                        };
                        Providers.Add(asm, list);
                    }
                }
            }
        }
    }
}
